package com.itheima.servise.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.anno.Log;
import com.itheima.controller.exception.ClazzBusinessException;
import com.itheima.mapper.ClazzMapper;
import com.itheima.mapper.StudentMapper;
import com.itheima.pojo.Clazz;
import com.itheima.pojo.ClazzQueryParam;
import com.itheima.pojo.PageBean;
import com.itheima.servise.ClazzServise;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;


@Service
public class ClazzServiseImpl implements ClazzServise {
    @Autowired
    private ClazzMapper clazzMapper;

    @Autowired
    private StudentMapper studentMapper;

    @Override
    public List<Clazz> getAll() {
        List<Clazz> all = clazzMapper.getAll();
        return all;
    }

    @Log
    @Override
    public void addClass(Clazz clazz) {
        clazz.setCreateTime(LocalDateTime.now());
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.addClass(clazz);
    }

    // 删除班级信息
    @Log
    @Override
    public void deleteClass(Integer id) {
        Integer clazzId = id;
        Long count = studentMapper.selectCountByDeptId(clazzId);
        if(count>0){
            throw new ClazzBusinessException("该班级下有学生，不能删除");
        }

        clazzMapper.deleteClass(id);
    }

    @Override
    public Clazz getById(Integer id) {
        return clazzMapper.getById(id);
    }

    // 修改班级信息
    @Log
    @Override
    public void putClass(Clazz clazz) {
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.putClass(clazz);
    }

    // 分页查询
    @Override
    public PageBean page(ClazzQueryParam param) {
        PageHelper.startPage(param.getPage(), param.getPageSize());
        List<Clazz> rows = clazzMapper.list(param);
        Page<Clazz> p = (Page<Clazz>) rows;
        p.forEach(clazz -> {
            LocalDate beginDate = clazz.getBeginDate();
            LocalDate endDate = clazz.getEndDate();
            LocalDate now = LocalDate.now();
            if (now.isAfter(endDate)) {
                clazz.setStatus("已结课");
            } else if (now.isAfter(beginDate)&& now.isBefore(endDate)) {
                clazz.setStatus("在读");
            } else {
                clazz.setStatus("未开班");
            }
        });
        return new PageBean(p.getTotal(), p.getResult());

    }

}

